package demo.service;

import com.alibaba.fastjson.JSONObject;
import demo.annotation.MethodCache;
import demo.util.DateTimeUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

//@Service
public class MongoService {

    private static Logger logger = LoggerFactory.getLogger(MongoService.class);

    @Autowired
    @Qualifier("lakeMongoTemplate")
    private MongoTemplate mongoTemplate;

    @Autowired
    @Qualifier("galaxyMongoTemplate")
    private MongoTemplate galaxyMongoTemplate;

    public Object queryCollectionById(String collectionName, String id) {
        return mongoTemplate.findById(id, Object.class, collectionName);
    }

    @MethodCache(expire = 300L, keyPattern = "mongo.{0}.{1}")
    public JSONObject findCollectionById(String collectionName, String id) {
        Object o = mongoTemplate.findById(id, Object.class, collectionName);
        return (JSONObject) JSONObject.toJSON(o);
    }

    /**
     * 通过ObjectId查询某天的所有数据（指定字段）
     *
     * @param collectionName
     * @param date
     * @return
     */
    public List<Object> queryDataByDate(String collectionName, LocalDate date) {
        // 指定返回的字段
        Document fieldsObject = new Document();
        fieldsObject.put("user_id", true);
        fieldsObject.put("create_time", true);

        LocalDateTime startInclude = date.atStartOfDay();
        LocalDateTime endExclude = date.plusDays(1).atStartOfDay();
        // 查询条件
        ObjectId minInclude = new ObjectId(DateTimeUtils.from(startInclude));
        ObjectId maxExclude = new ObjectId(DateTimeUtils.from(endExclude));

        Document queryObject = new Document();
        Document idDucoment = new Document();
        idDucoment.put("$gte", minInclude);
        idDucoment.put("$lt", maxExclude);
        queryObject.put("_id", idDucoment);

        Query query = new BasicQuery(queryObject, fieldsObject);
        return mongoTemplate.find(query, Object.class, collectionName);
    }

    /**
     * distinct某个字段查询
     *
     * @param collectionName
     * @param field
     * @return
     */
//    public <T> List<T> distinct(String collectionName, String field, Class<T> cls) {
//        DistinctIterable<T> distinctIterable = mongoTemplate.getCollection(collectionName).distinct(field, cls);
//        int batchSize = 5000;
//        distinctIterable.batchSize(batchSize);
//        ArrayList<T> list = new ArrayList<>();
//        list.ensureCapacity(batchSize);
//        distinctIterable.into(list);
//        return list;
//    }

//    public static boolean checkMongoTemplate(MongoTemplate mongoTemplate) {
//        String serverAddress = null;
//        boolean ok = false;
//        try {
//            Object obj = mongoTemplate.getDb();
//            if (obj instanceof DB) {
//                DB db = (DB) obj;
//                serverAddress = db.getName();
//                CommandResult pingResult = db.command("ping");
//                ok = pingResult.ok();
//            } else if (obj instanceof MongoDatabase) {
//                MongoDatabase db = (MongoDatabase) obj;
//                serverAddress = db.getName();
//                BsonDocument ping = BsonDocument.parse("{ping:1}");
//                Document document = db.runCommand(ping);
//                logger.info("runCommand(ping) return:{}", document);
//                logger.info(document.toJson());
//                Double result = document.getDouble("ok");
//                ok = result != null && result.doubleValue() == 1.0;
//            }
//            if (ok) {
//                logger.info("ping mongo {} ok.", serverAddress);
//            } else {
//                logger.error("ping mongo {} not ok.", serverAddress);
//            }
//        } catch (Exception e) {
//            logger.error("校验Mongo异常：{}", e.getMessage());
//        }
//        return ok;
//    }

}
